<script setup>
  import AppBar from '@/components/app-bar/app-bar.vue'
  import 'vue-cropper/dist/index.css'
  import { VueCropper } from 'vue-cropper'
  // import { upload } from '@/api/config'
  import { userProfile } from '@/api/user'
  import { ref } from 'vue'
  import { Toast } from 'vant'
  import { useI18n } from 'vue-i18n'

  const { t } = useI18n()
  const emit = defineEmits(['closeCode'])
  defineProps({
    showCropper: {
      type: Boolean,
      default: false
    }
  })

  const cropper = ref(null) // ref

  const modelSrc = ref('') // 生成图片数据
  const crap = ref(true)
  // const downImg = ref('') // 下载链接
  const previews = ref({}) // 实时预览
  const fixed = ref(true) // 浮动
  const fixedNumber = ref([16, 16]) // 截图比例
  const option = ref({
    img: '',
    size: 1,
    full: false,
    outputType: 'png',
    canMove: true,
    fixedBox: false,
    original: false,
    canMoveBox: true,
    autoCrop: true,
    // 只有自动截图开启 宽度高度才生效
    autoCropWidth: 160,
    autoCropHeight: 150,
    centerBox: false,
    high: true,
    max: 99999
  })

  const backSet = () => {
    emit('closeCode')
  }

  // start 移动背景图
  const startCrop = () => {
    crap.value = true
    cropper.value.startCrop()
  }

  // stop 禁止移动背景图
  const stopCrop = () => {
    crap.value = false
    cropper.value.stopCrop()
  }

  // 重新加载
  const refreshCrop = () => {
    cropper.value.refresh()
  }

  // 清除选择框
  const clearCrop = () => {
    cropper.value.clearCrop()
  }

  // 放大缩小背景图片
  const changeScale = (num) => {
    num = num || 1
    cropper.value.changeScale(num)
  }

  // 左旋转
  const rotateLeft = () => {
    cropper.value.rotateLeft()
  }

  // 右旋转
  const rotateRight = () => {
    cropper.value.rotateRight()
  }

  // 输出
  const finish = (type) => {
    if (type === 'blob') {
      cropper.value.getCropBlob((data) => {
        console.log(data)
        var img = window.URL.createObjectURL(data)
        modelSrc.value = img
        console.log(modelSrc.value)
      })
    } else {
      cropper.value.getCropData((data) => {
        modelSrc.value = data
        console.log(modelSrc.value)

        upUserAvatar(data)
      })
    }
  }

  const upUserAvatar = async (e) => {
    let params = {
      avatar: e
    }
    let res = await userProfile(params)
    emit('closeCode')
    console.log(res)
  }
  // 实时预览函数
  const realTime = (data) => {
    previews.value = data
    console.log(data)
  }

  // 下载
  // const down = (type) => {
  //   var aLink = document.createElement('a')
  //   aLink.download = 'demo'
  //   // 输出
  //   if (type === 'blob') {
  //     option.value.getCropBlob((data) => {
  //       downImg.value = window.URL.createObjectURL(data)
  //       aLink.href = window.URL.createObjectURL(data)
  //       aLink.click()
  //     })
  //   } else {
  //     option.value.getCropData((data) => {
  //       downImg.value = data
  //       aLink.href = data
  //       aLink.click()
  //     })
  //   }
  // }

  //上传图片
  const uploadImg = (e) => {
    var file = e.target.files[0]
    if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
      Toast(t('cropper.tips'))
      return false
    }
    var reader = new FileReader()
    reader.onload = (e) => {
      let data
      if (typeof e.target.result === 'object') {
        // 把Array Buffer转化为blob 如果是base64不需要
        data = window.URL.createObjectURL(new Blob([e.target.result]))
      } else {
        data = e.target.result
      }

      option.value.img = data
    }
    // 转化为base64
    // reader.readAsDataURL(file)
    // 转化为blob
    reader.readAsArrayBuffer(file)
  }

  const imgLoad = (msg) => {
    console.log(msg)
  }

  const cropMoving = (data) => {
    console.log(data, '截图框当前坐标')
  }
</script>
<template>
  <transition name="slide-fade-left">
    <div v-if="showCropper" class="cropper">
      <app-bar :else-back="true" @back-set="backSet">
        <template #title>{{ t('cropper.title') }}</template>
      </app-bar>
      <div class="cut">
        <vue-cropper
          ref="cropper"
          :img="option.img"
          :output-size="option.size"
          :output-type="option.outputType"
          :info="true"
          :full="option.full"
          :fixed="fixed"
          :fixed-number="fixedNumber"
          :can-move="option.canMove"
          :can-move-box="option.canMoveBox"
          :fixed-box="option.fixedBox"
          :original="option.original"
          :auto-crop="option.autoCrop"
          :auto-crop-width="option.autoCropWidth"
          :auto-crop-height="option.autoCropHeight"
          :center-box="option.centerBox"
          :high="option.high"
          mode="cover"
          :max-img-size="option.max"
          @real-time="realTime"
          @img-load="imgLoad"
          @crop-moving="cropMoving"
        ></vue-cropper>
      </div>
      <!-- 实时预览 -->
      <div
        v-if="false"
        class="show-preview"
        :style="{
          width: previews.w + 'px',
          height: previews.h + 'px',
          overflow: 'hidden',
          margin: '5px'
        }"
      >
        <div :style="previews.div">
          <img :src="previews.url" :style="previews.img" />
        </div>
      </div>
      <div class="test-button">
        <!-- <button class="btn" @click="changeImg">changeImg</button> -->
        <label class="btn" for="uploads">{{ t('cropper.itme1') }}</label>
        <input
          id="uploads"
          type="file"
          style="position: absolute; clip: rect(0 0 0 0)"
          accept="image/png, image/jpeg, image/gif, image/jpg"
          @change="uploadImg($event)"
        />
        <button v-if="!crap" class="btn" @click="startCrop">{{ t('cropper.itme2') }}</button>
        <button v-else class="btn" @click="stopCrop">{{ t('cropper.itme3') }}</button>
        <button class="btn" @click="clearCrop">{{ t('cropper.itme4') }}</button>
        <button class="btn" @click="refreshCrop">{{ t('cropper.itme5') }}</button>
        <button class="btn" @click="changeScale(1)">{{ t('cropper.itme6') }}</button>
        <button class="btn" @click="changeScale(-1)">{{ t('cropper.itme7') }}</button>
        <button class="btn" @click="rotateLeft">{{ t('cropper.itme8') }}</button>
        <button class="btn" @click="rotateRight">{{ t('cropper.itme9') }}</button>
        <!-- <button class="btn" @click="finish('base64')">{{ t('cropper.itme10') }}(base64)</button> -->
        <!-- <button class="btn" @click="finish('blob')">{{ t('cropper.itme10') }}</button> -->
        <!-- <a class="btn" @click="down('base64')">{{ t('cropper.itme11') }}(base64)</a>
        <a class="btn" @click="down('blob')">{{ t('cropper.itme11') }}(blob)</a> -->
        <a class="btn" @click="() => (option.img = '')">{{ t('cropper.itme12') }}</a>
        <div v-if="false" style="display: block; width: 100%">
          <label class="c-item">
            <span>{{ t('cropper.input1') }}</span>
            <input v-model="option.original" type="checkbox" />
            <span>original: {{ option.original }}</span>
          </label>
          <label class="c-item">
            <span>{{ t('cropper.input2') }}</span>
            <input v-model="option.canMove" type="checkbox" />
          </label>
          <label class="c-item">
            <span>{{ t('cropper.input3') }}</span>
            <input v-model="option.canMoveBox" type="checkbox" />
            <span>canMoveBox: {{ option.canMoveBox }}</span>
          </label>
          <label class="c-item">
            <span>{{ t('cropper.input4') }}</span>
            <input v-model="option.fixedBox" type="checkbox" />
            <span>fixedBox: {{ option.fixedBox }}</span>
          </label>
          <label class="c-item">
            <span>{{ t('cropper.input5') }}</span>
            <input v-model="option.full" type="checkbox" />
            <span>full: {{ option.full }}</span>
          </label>
          <label class="c-item">
            <span>{{ t('cropper.input6') }}</span>
            <input v-model="option.autoCrop" type="checkbox" />
            <span>autoCrop: {{ option.autoCrop }}</span>
          </label>
          <label class="c-item">
            <span>{{ t('cropper.input7') }}</span>
            <input v-model="option.high" type="checkbox" />
            <span>high: {{ option.high }}</span>
          </label>
          <label class="c-item">
            <span>{{ t('cropper.input8') }}</span>
            <input v-model="option.centerBox" type="checkbox" />
            <span>centerBox: {{ option.centerBox }}</span>
          </label>
          <label class="c-item">
            <p>{{ t('cropper.input9') }}</p>
            <label
              >jpg
              <input v-model="option.outputType" type="radio" name="type" value="jpeg" />
            </label>
            <label
              >png
              <input v-model="option.outputType" type="radio" name="type" value="png" />
            </label>
            <label
              >webp
              <input v-model="option.outputType" type="radio" name="type" value="webp" />
            </label>
          </label>
        </div>
      </div>
      <div class="submit" @click="finish('base64')">{{ t('cropper.submit') }}</div>
    </div>
  </transition>
</template>
<style lang="scss" scoped>
  .cropper {
    width: 100%;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    background: #000000;
    padding-top: 45px;
    .cut {
      width: 100%;
      height: 300px;
      margin: 30px auto;
    }

    .c-item {
      max-width: 800px;
      margin: 10px auto;
      margin-top: 20px;
    }

    .test-button {
      display: flex;
      flex-wrap: wrap;
      align-content: center;
      justify-content: center;
    }

    .btn {
      display: inline-block;
      line-height: 1;
      white-space: nowrap;
      cursor: pointer;
      background: #fff;
      border: none;
      color: #1f2d3d;
      text-align: center;
      box-sizing: border-box;
      outline: none;
      margin: 20px 10px 0px 0px;
      padding: 9px 15px;
      font-size: 14px;
      border-radius: 4px;
      color: #fff;
      background-image: linear-gradient(0deg, #e2ba7c 0%, #eeca8c 100%);
      transition: all 0.2s ease;
      text-decoration: none;
      user-select: none;
    }

    .c-item {
      display: block;
      user-select: none;
    }

    .submit {
      margin: 15px 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      color: #ffffff;
      background: linear-gradient(0deg, #e2ba7c 0%, #eeca8c 100%);
      border-radius: 20px;
      color: #714d13;
    }
  }
</style>
